package com.yanxinim.cn.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.adapter.NewsAdapter;
import com.yanxinim.cn.bean.news.NewsResultData;
import com.yanxinim.cn.store.Goods;
import com.yanxinim.cn.store.StoreGoodsAdapter;
import com.yanxinim.cn.store.StoreGoodsDetailsActivity;
import com.yanxinim.cn.store.StoreHomeActivity;
import com.yanxinim.cn.store.ViewPagerAdapter;
import com.yanxinim.cn.store.adapter.TypeAdapter;
import com.yanxinim.cn.store.bean.ProductType;
import com.yanxinim.cn.ui.base.EasyFragment;
import com.yanxinim.cn.util.HttpUtil;
import com.yanxinim.cn.util.JsonTool;
import com.yanxinim.cn.util.JsonUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class StoreGoodsFragment extends EasyFragment {
    NewsResultData newsResultData;
    NewsAdapter goodsAdapter;
    private SmartRefreshLayout srlRefresh;
    private RecyclerView rvNewsList;
    private ImageView ivNothing;
    private Context context;

    private String status;
    private String name;
    private StoreGoodsAdapter storeGoodsAdapter;
    private int page = 0;
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            newsResultData = JsonTool.jsonToObject(String.valueOf(msg.obj), NewsResultData.class);
            goodsAdapter = new NewsAdapter(context, newsResultData.getResult().getData());
            rvNewsList.setAdapter(goodsAdapter);
        }
    };

    public StoreGoodsFragment() {
    }

    public static StoreGoodsFragment getInstance(String status,String name) {
        StoreGoodsFragment fragment = new StoreGoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        bundle.putString("name", name);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.a_news_list_fragment;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        context = getActivity();
        Bundle bundle = getArguments();
        if (bundle != null) {
            status = bundle.getString("status");
            name = bundle.getString("name");
        }
        srlRefresh = findViewById(R.id.srl_refresh);
        rvNewsList = findViewById(R.id.rv_news_list);
        ivNothing = findViewById(R.id.iv_nothing);

        rvNewsList.setLayoutManager(new LinearLayoutManager(context));

        srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 0;
                initData();
            }
        });
        srlRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initData();
            }
        });
        initData();
    }

    public void initData() {

        Map<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("limit", String.valueOf(10));

        String url = "";
        if (status == null)
            return;
        if (name.equals("全部")) {
            url = AppConfig.STORE_GOODS;
        } else {
            params.put("categoryId", status);
            url = AppConfig.STORE_CATEGORY_GOODS;
        }

        HttpUtils.get().url(url)
                .params(params)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                    if (jsonObject.getInteger("resultCode") == 1) {
                        JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
                        List<Goods> goodsList = JsonTool.jsonToList(jsonObject1.getString("pageData"), Goods.class);
                        if (goodsList != null && goodsList.size() > 0) {
                            ivNothing.setVisibility(View.GONE);
                            if (page == 0) {
                                storeGoodsAdapter = new StoreGoodsAdapter(context, goodsList, 1);
                                storeGoodsAdapter.setAdapterOnClickListener(new StoreGoodsAdapter.AdapterOnClickListener() {
                                    @Override
                                    public void onClick(int position, Goods data) {
                                        Intent intent = new Intent(context, StoreGoodsDetailsActivity.class);
                                        intent.putExtra("productId", data.getId());
                                        startActivity(intent);
                                    }
                                });
                                rvNewsList.setAdapter(storeGoodsAdapter);
                            } else {
                                if (storeGoodsAdapter != null) {
                                    storeGoodsAdapter.addAllData(goodsList);
                                }
                            }
                            if (goodsList.size() != 10) {
                                srlRefresh.setEnableLoadMore(false);
                            }

                        } else {
                            if (page == 0) {
                                ivNothing.setVisibility(View.VISIBLE);
                            } else {
                                ivNothing.setVisibility(View.GONE);
                            }
                            srlRefresh.setEnableLoadMore(false);
                        }

                    }
                    srlRefresh.finishRefresh();
                    srlRefresh.finishLoadMore();
                    Log.i("qin_store", result);
                });

            }
        });

    }
}
